package org.niu.listnode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseBetween {
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        ListNode p = head;
        ListNode p1 = head;
        ListNode newHead = new ListNode(-1);
        ListNode tail = newHead;
        if(head == null) return null;
        int len = 0;
        while (p!=null){
            p=p.next;
            len++;
        }
        int[] a = new int[len+1];
        int[] b = new int[n-m+1];
        len = 0;
        while (p1!=null){
            a[len++]=p1.val;
            p1=p1.next;
        }

        for (int i = n-1,j=0; i >= m && j < b.length; i--,j++) {
            b[j] = a[i];
        }
        for (int i = 0;i < a.length;i++){
            ListNode t = null;
            if(i <= m || i >= n){
                t = new ListNode(a[i]);
            }else{
                t = new ListNode(b[i-m]);
            }
            tail.next = t;
            tail = tail.next;

        }
        return newHead.next;
    }
}
